package com.whfc.wxmp.jwt;

import com.whfc.fuum.entity.SysUser;
import com.whfc.fuum.entity.WxUser;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    // 建议放到配置文件
    private static final String SECRET_KEY = "your-256-bit-secret-your-256-bit-secret"; // 长度要足够
    private static final long EXPIRATION = 60L * 24 * 60 * 60 * 1000; // 60天

    // 生成token
    public static String generateToken(WxUser wxUser, SysUser sysUser) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", wxUser.getId());
        claims.put("name", wxUser.getName());
        claims.put("phone", wxUser.getPhone());
        claims.put("openId", wxUser.getOpenId());
        claims.put("appType", wxUser.getAppType());

//        claims.put("sysUserId", sysUser.getId());

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(String.valueOf(wxUser.getId()))
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY.getBytes())
                .compact();
    }

    // 解析token
    public static Claims parseToken(String token) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY.getBytes())
                .parseClaimsJws(token)
                .getBody();
    }
}